package com.qf.shiro;

import com.alibaba.druid.util.StringUtils;
import com.qf.pojo.DtsAdmin;
import com.qf.service.AdminService;
import com.qf.service.PermissionService;
import com.qf.service.RoleService;
import com.qf.util.bcrypt.BCryptPasswordEncoder;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.Set;

public class AdminAuthorizingRealm extends AuthorizingRealm {
    @Autowired
    private AdminService adminService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private PermissionService permissionService;
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        DtsAdmin admin = (DtsAdmin) getAvailablePrincipal(principalCollection);
        Integer[] ids = admin.getRoleIds();
        Set<String> role = roleService.queryByIds(ids);
        Set<String> permisson = permissionService.queryPermissonByRoleIds(ids);
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setRoles(role);
        info.setStringPermissions(permisson);
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken usernameAndPas=(UsernamePasswordToken) authenticationToken;
        String username = usernameAndPas.getUsername();
        String password =new String( usernameAndPas.getPassword());
        if (StringUtils.isEmpty(username)){
            throw new AccountException("用户名为空!");
        }
        if ((StringUtils.isEmpty(password))){
            throw new AccountException("用户密码为空！");
        }
        List<DtsAdmin> adminList = adminService.findAdminByUserName(username);
        if (adminList==null||adminList.size()==0){
            throw new UnknownAccountException("用户名有误！");
        }
        if (adminList.size()>=2){
            throw new UnknownAccountException("存在相同的用户名，请联系管理员！");
        }
        DtsAdmin admin = adminList.get(0);
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        if (!encoder.matches(password,admin.getPassword())){
            throw new UnknownAccountException("密码有误");
        }
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(admin, password, this.getName());
        return info;
    }
}
